<template>
  <div class="login-container">
    <el-form
      v-if="state.type === 0"
      ref="refLoginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">登录</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon name="user" />
        </span>
        <el-input
          ref="refUsername"
          v-model="loginForm.username"
          placeholder="手机号"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>
      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon name="password" />
        </span>
        <el-input
          ref="refPassword"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          autocomplete="on"
          @keyup.enter="handleLogin"
        />
        <span class="show-pwd" @click="showPwd()">
          <svg-icon :name="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <div class="page-type-text">
        <span @click="state.type = 1"> 没有账号，去注册 </span>
      </div>
      <el-button
        :loading="loading"
        type="primary"
        size="large"
        style="width: 100%; margin-bottom: 30px"
        @click.prevent="handleLogin"
      >
        登 录
      </el-button>
    </el-form>

    <el-form
      v-else-if="state.type === 1"
      ref="refRegForm"
      :model="registerForm"
      :rules="regRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">注册</h3>
      </div>
      <p class="form-label">昵称由中文或者字母数字组成，长度在1到10位之间</p>
      <el-form-item prop="nickname">
        <span class="svg-container">
          <svg-icon name="user" />
        </span>
        <el-input
          ref="refUsername"
          v-model="registerForm.nickname"
          placeholder="用户名"
          name="nickname"
          type="text"
        />
      </el-form-item>
      <p class="form-label">手机号码必须是11位</p>
      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon name="user" />
        </span>
        <el-input
          ref="refUsername"
          v-model="registerForm.username"
          placeholder="手机号"
          name="username"
          type="text"
        />
      </el-form-item>
      <el-form-item prop="vercode">
        <span class="svg-container">
          <svg-icon name="user" />
        </span>
        <el-input
          ref="refUsername"
          v-model="registerForm.vercode"
          placeholder="验证码"
          maxlength="6"
          name="vercode"
          type="text"
        />
        <el-button
          type="primary"
          class="get-code"
          :disabled="codeState.disabled"
          @click="getCode"
          >{{ codeBtnText }}</el-button
        >
      </el-form-item>
      <p class="form-label">密码由大小写字母和数字组成，长度在8到20位</p>
      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon name="password" />
        </span>
        <el-input
          ref="refPassword"
          v-model="registerForm.password"
          type="password"
          placeholder="密码"
          name="password"
        />
      </el-form-item>
      <el-form-item prop="password1">
        <span class="svg-container">
          <svg-icon name="password" />
        </span>
        <el-input
          ref="refPassword"
          v-model="registerForm.password1"
          type="password"
          placeholder="确认密码"
          name="password"
        />
      </el-form-item>
      <div class="page-type-text">
        <span @click="state.type = 0">已有账号，去登录</span>
      </div>
      <el-button
        :loading="loading"
        type="primary"
        size="large"
        style="width: 100%; margin-bottom: 30px"
        @click.prevent="handleLogin"
      >
        注 册
      </el-button>
    </el-form>
  </div>
</template>

<script setup>
import { nextTick, onMounted, reactive, toRefs, computed } from 'vue'
import { useUserStore } from '@/store/user'
import { useRouter, useRoute } from 'vue-router'
import { register, getSmsCode } from '@/api/auth'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()

const validateUsername = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入账号'))
  } else {
    callback()
  }
}
const validatePassword = (rule, value, callback) => {
  if (value.length < 6) {
    callback(new Error('请输入有效密码'))
  } else {
    callback()
  }
}

const state = reactive({
  type: 0,
  refLoginForm: null,
  refRegForm: null,
  refUsername: null,
  refPassword: null,
  loginForm: {
    username: '',
    password: ''
  },
  loginRules: {
    username: [
      { required: true, trigger: 'blur', validator: validateUsername }
    ],
    password: [{ required: true, trigger: 'blur', validator: validatePassword }]
  },
  registerForm: {
    nickname: '',
    username: '',
    vercode: '',
    password: '',
    password1: ''
  },
  regRules: {
    nickname: [{ required: true, trigger: 'blur', message: '请输入 用户名' }],
    username: [{ required: true, trigger: 'blur', message: '请输入 手机号' }],
    vercode: [{ required: true, trigger: 'blur', message: '请输入 验证码' }],
    password: [{ required: true, trigger: 'blur', message: '请输入 密码' }],
    password1: [{ required: true, trigger: 'blur', message: '请输入 确认密码' }]
  },
  passwordType: 'password',
  loading: false,
  showDialog: false,
  redirect: undefined,
  otherQuery: {}
})

const codeState = reactive({
  disabled: false,
  time: 120,
  timer: null
})

const {
  refLoginForm,
  refUsername,
  refPassword,
  loginForm,
  loginRules,
  passwordType,
  loading,
  regRules,
  registerForm,
  refRegForm
} = toRefs(state)
const codeBtnText = computed(() => {
  if (codeState.timer) {
    return `${codeState.time}s 后重发`
  }
  return `获取验证码`
})

const getOtherQuery = (query) => {
  return Object.keys(query).reduce((acc, cur) => {
    if (cur !== 'redirect') {
      acc[cur] = query[cur]
    }
    return acc
  }, {})
}

const showPwd = () => {
  if (state.passwordType === 'password') {
    state.passwordType = ''
  } else {
    state.passwordType = 'password'
  }
  nextTick(() => {
    state.refPassword.focus()
  })
}

const getCode = async () => {
  if (codeState.disabled) return false
  if (!registerForm.value.username) return ElMessage.error('请输入有效手机号')
  await getSmsCode(registerForm.value.username)
  codeState.disabled = true
  codeState.timer = setInterval(() => {
    codeState.time = codeState.time - 1
    if (codeState.time <= 0) {
      clearInterval(codeState.timer)
      codeState.timer = null
      codeState.disabled = false
      codeState.time = 120
    }
  }, 1000)
}

const handleLogin = () => {
  if (state.type === 0) {
    state.refLoginForm.validate(async (valid) => {
      if (valid) {
        state.loading = true
        const userStore = useUserStore()
        try {
          await userStore.login({
            username: loginForm.value.username,
            password: loginForm.value.password
          })
          router.push({ path: state.redirect || '/', query: state.otherQuery })
        } finally {
          state.loading = false
        }
      } else {
        return false
      }
    })
  } else if (state.type === 1) {
    state.refRegForm.validate(async (valid) => {
      if (valid) {
        const { nickname, username, vercode, password, password1 } =
          registerForm.value
        await register({
          nickname,
          username,
          verCode: vercode,
          password,
          password1
        })
        state.type = 0
        loginForm.value.username = registerForm.value.username
        state.refRegForm.resetFields()
        ElMessage.success('注册成功')
      } else {
        return false
      }
    })
  }
}

onMounted(() => {
  const { query } = route
  if (state.loginForm.username === '') {
    state.refUsername.focus()
  } else if (state.loginForm.password === '') {
    state.refPassword.focus()
  }
  if (query) {
    state.redirect = query.redirect
    state.otherQuery = getOtherQuery(query)
  }
})
</script>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
$cursor: #fff;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  :deep(.el-input) {
    flex: 1;
    display: inline-block;
    height: 47px;

    .el-input__wrapper {
      width: 100%;
      padding: 0;
      background-color: transparent;
      box-shadow: none;

      input {
        background: transparent;
        border: 0px;
        appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }

  .form-label {
    color: #ccc;
    padding-bottom: 4px;
  }

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    box-sizing: border-box;
    margin: 0 auto;
    overflow: hidden;
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
}

.page-type-text {
  color: #20a0ff;
  padding: 0 0 20px;
  text-align: right;
  user-select: none;
  & > span {
    cursor: pointer;
  }
}
.get-code {
  margin-right: 10px;
}
</style>
